package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.constants.GreenScanConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.exception.CustomException;
import com.heima.common.tess4j.Tess4jClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Xiao
 * @version 1.0
 * @description
 * @date 2021/11/23
 */
@Service
@Slf4j
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {
    @Autowired
    private WmNewsMapper wmNewsMapper;
    /**
     * 文章审核
     * @param wmNewsId
     */
    @Override
    @Async
    public void autoScanWmNews(Integer wmNewsId) {
        //1.查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(wmNewsId);
        if (ObjectUtil.isEmpty(wmNews)) {
            throw new RuntimeException("WmNewsAutoScanServiceImpl-文章不存在");
        }
        //检查状态（待审核）
        if (WemediaConstants.WM_NEWS_STATUS_SCAN_WAITING.equals(wmNews.getStatus())) {
            //从内容中提取取文本内容和图片
            Map<String, Object> textAndImages = getTextAndImages(wmNews);
            String text = (String) textAndImages.get(WemediaConstants.WM_NEWS_TYPE_TEXT);
            //文本 --> 自管理的敏感词过滤
            Boolean flag = textSensitiveScan(text, wmNews);
            log.info("文本敏感词审核结果：{}", flag);
            if (!flag) {
                return;
            }
            //2.阿里云审核文本内容 --> 成功(下一步)，失败(修改文章审核状态、结束)
            flag = textScan(text, wmNews);
            log.info("文本审核结果：{}", flag);
            if (!flag) {
                return;
            }
            //3.本地敏感词/阿里云审核图片 --> 成功(下一步)，失败(修改文章审核状态、结束)
            List<String> images = (List<String>) textAndImages.get(WemediaConstants.WM_NEWS_TYPE_IMAGE);
            flag = imagesScan(images, wmNews);
            log.info("图片审核结果：{}", flag);
            if (!flag) {
                return;
            }
            //4.审核成功，保存app端的相关的文章数据
            ResponseResult result = saveAppArticle(wmNews);
            log.info("app文章发布结果：{}", result.getCode());
            log.info("app文章id：{}", result.getData());
            if(AppHttpCodeEnum.SUCCESS.getCode() != (result.getCode())){
                throw new RuntimeException("WmNewsAutoScanServiceImpl-文章审核，保存app端相关文章数据失败");
            }
            //回填article_id
            wmNews.setArticleId(Long.valueOf(result.getData().toString()));
            updateWmNews(wmNews,
                    WemediaConstants.WM_NEWS_STATUS_SCAN_PUBLISH,
                    WemediaConstants.WM_NEWS_REASON_PASS);
        }
    }

    @Autowired
    private WmSensitiveMapper sensitiveMapper;
    /**
     * 检测文本内容是否包含敏感词
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean textSensitiveScan(String text, WmNews wmNews) {
        Boolean flag = true;
        //获取所有敏感词
        List<WmSensitive> wmSensitives = sensitiveMapper.selectList(
                Wrappers.<WmSensitive>lambdaQuery()
                .select(WmSensitive::getSensitives));
        List<String> sensitiveWords = wmSensitives
                .stream()
                .map(WmSensitive::getSensitives)
                .collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveWords);
        //检测文本内容是否包含敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if (CollUtil.isNotEmpty(map)) {
            updateWmNews(wmNews,
                    WemediaConstants.WM_NEWS_STATUS_SCAN_FAIL,
                    WemediaConstants.WM_NEWS_REASON_ILLEGAL_TESS4J + map);
            flag = false;
        }
        return flag;
    }

    @Autowired
    private WmChannelMapper wmChannelMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IArticleClient articleClient;
    /**
     * 保存app端的相关的文章数据
     * @param wmNews
     * @return
     */
    private ResponseResult saveAppArticle(WmNews wmNews) {
        //属性拷贝
        ArticleDto dto = new ArticleDto();
        BeanUtil.copyProperties(wmNews, dto, "id");
        //属性填充
        //布局
        dto.setLayout(wmNews.getType());
        //频道
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (ObjectUtil.isNotEmpty(wmChannel)) {
            dto.setChannelName(wmChannel.getName());
        }
        //作者
        dto.setAuthorId(wmNews.getUserId());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (ObjectUtil.isNotEmpty(wmUser)) {
            dto.setAuthorName(wmUser.getName());
        }
        //文章id
        if (ObjectUtil.isNotEmpty(wmNews.getArticleId())) {
            dto.setId(wmNews.getArticleId());
        }
        //创建时间
        dto.setCreatedTime(new Date());
        //保存文章
        ResponseResult responseResult = articleClient.saveArticle(dto);
        if (AppHttpCodeEnum.SUCCESS.getCode() != responseResult.getCode()) {
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        return responseResult;
    }

    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private Tess4jClient tess4jClient;

    /**
     * 审核图片  阿里云接口 --> 成功(下一步)，失败(修改文章审核状态、结束)
     * @param images
     * @param wmNews
     * @return
     */
    private Boolean imagesScan(List<String> images, WmNews wmNews) {
        Boolean flag = true;
        if (CollUtil.isEmpty(images)) {
            return flag;
        }
        //下载图片 minIO
        //图片去重
        images = images.stream().distinct().collect(Collectors.toList());
        List<byte[]> imagesByte = new ArrayList<>();
        try {
            for (String image : images) {
                byte[] bytes = fileStorageService.downLoadFile(image);
                imagesByte.add(bytes);
                //检测图片中是否包含敏感词
                //byte[]转换为butteredImage
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                BufferedImage imageFile = ImageIO.read(bais);
                //提取图片中的文字
                String text = tess4jClient.doOCR(imageFile);
                System.err.println("提取图片中的文字：");
                System.out.println(text);
                //审核图片中的文字
                flag = StringUtils.isNotBlank(text) ? textSensitiveScan(text, wmNews) : flag;
                if (!flag) {
                    return flag;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            Map<String, String> resultMap = greenImageScan.imageScan(imagesByte);
            if (CollUtil.isNotEmpty(resultMap)) {
                String suggestion = resultMap.get(GreenScanConstants.GREEN_SCAN_KEY);
                //block-->违规内容
                if (GreenScanConstants.GREEN_SCAN_VALUE_BLOCK.equals(suggestion)) {
                    flag = false;
                    updateWmNews(wmNews,
                            WemediaConstants.WM_NEWS_STATUS_SCAN_FAIL,
                            WemediaConstants.WM_NEWS_REASON_ILLEGAL_IMAGE);
                }
                //review-->人工审核
                if (GreenScanConstants.GREEN_SCAN_VALUE_REVIEW.equals(suggestion)) {
                    flag = false;
                    updateWmNews(wmNews,
                            WemediaConstants.WM_NEWS_STATUS_SCAN_PERSON,
                            WemediaConstants.WM_NEWS_REASON_UNSURE_IMAGE);
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 审核文本内容：阿里云接口 --> 成功(下一步)，失败(修改文章审核状态、结束)
     * @param text
     * @param wmNews
     * @return
     */
    private Boolean textScan(String text, WmNews wmNews) {
        Boolean flag = true;
        if(StringUtils.equals(text, "-")){
            return flag;
        }
        try {
            Map<String, String> resultMap = greenTextScan.greeTextScan(text);
            if (CollUtil.isNotEmpty(resultMap)) {
                String suggestion = resultMap.get(GreenScanConstants.GREEN_SCAN_KEY);
                //block-->违规内容
                if (GreenScanConstants.GREEN_SCAN_VALUE_BLOCK.equals(suggestion)){
                    flag = false;
                    updateWmNews(wmNews,
                            WemediaConstants.WM_NEWS_STATUS_SCAN_FAIL,
                            WemediaConstants.WM_NEWS_REASON_ILLEGAL_TEXT);
                }
                //review-->人工审核
                if (GreenScanConstants.GREEN_SCAN_VALUE_REVIEW.equals(suggestion)) {
                    flag = false;
                    updateWmNews(wmNews,
                            WemediaConstants.WM_NEWS_STATUS_SCAN_PERSON,
                            WemediaConstants.WM_NEWS_REASON_UNSURE_TEXT);
                }
            }
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 修改自媒体文章审核状态、审核原因，审核成功后填充app文章id
     * @param wmNews
     */
    private void updateWmNews(WmNews wmNews, Integer status, String reason) {
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 从内容中提取文本内容和图片
     * @param wmNews
     * @return
     */
    private Map<String, Object> getTextAndImages(WmNews wmNews) {
        StringBuilder text = new StringBuilder();
        List<String> images = new ArrayList<>();
        if (StringUtils.isNotBlank(wmNews.getTitle())) {
            text.append(wmNews.getTitle()).append("-");
        }
        //提取自媒体文章内容中的文案和图片
        if (StringUtils.isNotBlank(wmNews.getContent())) {
            List<Map> maps = JSON.parseArray(wmNews.getContent(), Map.class);
            for (Map map : maps) {
                String type = (String) map.get(WemediaConstants.WM_NEWS_TYPE);
                String value = (String) map.get(WemediaConstants.WM_NEWS_VALUE);
                if (WemediaConstants.WM_NEWS_TYPE_TEXT.equals(type)) {
                    text.append(value);
                }
                if (WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(type)) {
                    images.add(value);
                }
            }
        }
        //提取封面中的图片
        if (StringUtils.isNotBlank(wmNews.getImages())) {
            String[] coverImages = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(coverImages));
        }
        Map<String, Object> textAndImages = new HashMap<>();
        textAndImages.put(WemediaConstants.WM_NEWS_TYPE_TEXT, text.toString());
        textAndImages.put(WemediaConstants.WM_NEWS_TYPE_IMAGE, images);
        return textAndImages;
    }
}
